//
//  MainViewController.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/6.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addChildViewControllers()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //创建tabItem之后创建button
        setupComposeButton()
    }
    
    /// 撰写 按钮点击事件
    @objc private func clickComposeButton() {
        
        var viewController = UIViewController()
        
        if UserAccountViewModel.sharedUserAccount.userLogon {
            viewController = ComposeViewController()
        } else {
            viewController = OAuthViewController()
        }
        
        let nav = UINavigationController(rootViewController: viewController)

        presentViewController(nav, animated: true, completion: nil)
        
        
    }
    
    /// 懒加载撰写按钮
    private lazy var composeButton = UIButton(imageName: "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}

// MARK: - 设置控制器
extension MainViewController {
    
    //设置撰写按钮
    private func setupComposeButton() {
        tabBar.addSubview(composeButton)
        let count = childViewControllers.count
        let width = tabBar.bounds.width / CGFloat(count) - 1
        
        composeButton.frame = CGRectInset(tabBar.bounds, width * 2, 0)
        //添加点击事件
        composeButton.addTarget(self, action: "clickComposeButton", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    /// 设置所有控制器
    private func addChildViewControllers() {
        
        addChildViewController(HomeTableViewController(), title: "主页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        //占位
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我的", imageName: "tabbar_profile")
        
    }
    
    /// 设置控制器
    /// - parameter title: 标题
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
}
